# -*- coding:utf-8 -*-
# Xpath解析
"""
XPath，全称 XML Path Language，即 XML 路径语言，
它是一门在 XML 文档中查找信息的语言。XPath可用来在XML文档中对元素和属性进行遍历。
"""

# xpath原理
"""
1. 实例化一个etree的对象，且需要将被解析的页面源码数据加载到该对象中
2. 调用etree对象中的xpath方法结合xpath表达式实现标签的定位和内容的捕获
"""

from lxml import etree

html_doc = """
<html><head><title>The Dormouse's story</title></head>
    <body>
        <p class="title"><b>The Dormouse's story</b></p>
        <p class="story">Once upon a time there were three little sisters; and their names were
            <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
            <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
            <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
            and they lived at the bottom of a well.
        </p>

<p class="story">...</p>
"""

# 创建一个HTML对象，解析html字符串
html = etree.HTML(html_doc)

# //找在整个文档中找全部的标签，/在//找到的路径下，一级一级往下找,如：
# //学校[@望子成龙=湖南长沙岳麓]/三年级/二班/小明

# data = html.xpath("//a")
# print(data)

# student = //学校[@望子成龙=湖南长沙岳麓]/三年级/二班  for num in student  num./xiaoming


# 在整个文档中寻找body下面带有class="story"属性的p标签，下面全部的a标签
# 注意：寻找的第一个标签要么标签唯一， 要么标签的属性唯一
data = html.xpath('//body/p[@class="story"]//a')
# print(data)
# data = html.xpath('//p[@class="story"]//a')         # 与上面一样的结果
for num in data:
    # 在a标签当中获取他的文本值
    name = num.xpath("./text()")[0]
    href = num.xpath("./@href")[0]
    print(name, href)
